﻿using HY.Common;
using HY.Entity;
using HY.Service;
using HY.Web.Controllers;
using HY.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;

namespace HY.Web.Areas.System.Controllers
{
    public class SysRoleController : BaseController
    {
        SysRoleService service = new SysRoleService();
        // GET: System/SysRole
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult List(int page, int limit)
        {
            ReturnModel returnModel = new ReturnModel();
            try
            {
                var roleName = Request.Form["roleName"];
                Expression<Func<SysRole, bool>> where = (m => m.IsDeleted == false);
                if (!string.IsNullOrWhiteSpace(roleName))
                    where = where.And(m => m.RoleName.Contains(roleName));
                List<OrderByExpression> order = new List<OrderByExpression>();
                order.Add(new OrderByExpression() { PropertyName = PropertySupport.GetPropertyName<SysRole>(a => a.RoleSort) });
                order.Add(new OrderByExpression() { PropertyName = PropertySupport.GetPropertyName<SysRole>(a => a.CreateDate), IsDesc = true });
                var tuple = service.EFGetPageList(where, page, limit, order.ToArray());
                returnModel = base.GetReturnModel(tuple.Item1, tuple.Item2);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                LogHelper.Error(new LogInfo() { UserID = UserInfo.UserID, LogType = LogType.Select, LogMessage = "查询角色列表" }, ex);
            }
            return Json(returnModel);
        }
        
        public ActionResult Add()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Add(SysRole model)
        {
            ReturnModel returnModel = new ReturnModel();
            LogInfo logInfo = new LogInfo() { UserID = base.UserInfo.UserID, LogType = LogType.Insert };
            try
            {
                model.CreateUserID = base.UserInfo.UserID;
                model.CreateDate = DateTime.Now;
                returnModel.count = service.Add(model);
                returnModel.msg = "保存成功";
                logInfo.LogMessage = $"角色{returnModel.msg}";
                LogHelper.Info(logInfo);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "保存失败";
                logInfo.LogMessage = $"角色{returnModel.msg}";
                LogHelper.Error(logInfo, ex);
            }
            return Json(returnModel);
        }

        public ActionResult Edit(int? id)
        {
            var model = service.GetById<SysRole>(id);
            return View(model);
        }

        [HttpPost]
        public JsonResult Edit(SysRole model)
        {
            ReturnModel returnModel = new ReturnModel();
            LogInfo logInfo = new LogInfo() { UserID = base.UserInfo.UserID, LogType = LogType.Update };
            try
            {
                var oldModel = service.GetById<SysRole>(model.ID);
                model.IsDeleted = oldModel.IsDeleted;
                model.CreateDate = oldModel.CreateDate;
                model.CreateUserID = oldModel.CreateUserID;
                model.LastModifyUserID = base.UserInfo.UserID;
                model.LastModifyDate = DateTime.Now;
                returnModel.count = service.Update(model);
                returnModel.msg = "保存成功";
                logInfo.LogMessage = $"角色{returnModel.msg}";
                LogHelper.Info(logInfo);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "保存失败";
                logInfo.LogMessage = $"角色{returnModel.msg}";
                LogHelper.Error(logInfo, ex);
            }
            return Json(returnModel);
        }

        public ActionResult RoleSet(int roleID)
        {
            var sysRoleModules = service.EFGetMany<SysRoleModule>(s => s.RoleID == roleID && !s.IsIndeterminate);
            StringBuilder sb = new StringBuilder();
            foreach(var item in sysRoleModules)
            {
                sb.Append("'");
                sb.Append(item.ModuleID);
                sb.Append("',");
            }
            ViewBag.roleID = roleID;
            ViewBag.moduleIDs = sb.ToString().TrimEnd(',');
            return View();
        }
        [HttpPost]
        public ActionResult RoleSet(int roleID,string modules)
        {
            ReturnModel returnModel = new ReturnModel();
            LogInfo logInfo = new LogInfo() { UserID = base.UserInfo.UserID, LogType = LogType.Insert };
            try
            {
                List<SysRoleModule> sysRoleModules = new List<SysRoleModule>();
                if (!string.IsNullOrWhiteSpace(modules))
                {
                    foreach (var module in modules.TrimEnd('|').Split('|'))
                    {
                        string[] temp = module.Split(',');
                        SysRoleModule model = new SysRoleModule();
                        model.ID = 15;
                        model.RoleID = roleID;
                        model.ModuleID = int.Parse(temp[0]);
                        model.IsIndeterminate = temp[1] == "1";
                        model.CreateUserID = base.UserInfo.UserID;
                        model.CreateDate = DateTime.Now;
                        sysRoleModules.Add(model);
                    }
                }
                SysModuleService sysModuleService = new SysModuleService();
                returnModel.count = sysModuleService.RoleSet(roleID, sysRoleModules);
                returnModel.msg = "保存成功";
                logInfo.LogMessage = $"权限{returnModel.msg}";
                LogHelper.Info(logInfo);
            }
            catch (Exception ex)
            {
                returnModel = base.GetReturnModel(ex);
                returnModel.msg = "保存失败";
                logInfo.LogMessage = $"权限{returnModel.msg}";
                LogHelper.Error(logInfo, ex);
            }
            return Json(returnModel);
        }
    }
}